package com.gk.javaservice.util.javaRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

public class HttpUtilNew {

    private static final Logger log = Logger.getLogger(HttpUtilNew.class);

    // 创建一个忽略SSL验证的HttpClient实例
    private static CloseableHttpClient createNoSSLClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
        SSLContext sslContext = new SSLContextBuilder()
                .loadTrustMaterial(null, (X509Certificate[] chain, String authType) -> true)
                .build();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        return HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
    }


    /**
     * 发送GET请求
     * @param url 请求URL
     * @param param 请求参数，格式为JSON对象，如无参可传null
     * @return 返回的JSON响应对象
     */
    public static JSONObject doGet(String url, JSONObject param) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        JSONObject responseJson = null;
        try {
            httpClient = createNoSSLClient(); // 使用忽略SSL验证的HttpClient
            URIBuilder builder = new URIBuilder(url);

            if (param != null && !param.isEmpty()) {
                for (String key : param.keySet()) {
                    Object value = param.get(key);
                    if (value instanceof String) {
                        builder.addParameter(key, (String) value);
                    }
                }
            }

            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5000)
                    .setSocketTimeout(30000)
                    .build();
            httpGet.setConfig(requestConfig);

            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String resultString = EntityUtils.toString(entity, "UTF-8");
            log.info("resultString:"+resultString);
            try {
                responseJson = JSONObject.parseObject(resultString);
            }catch (ClassCastException e){
//                responseJson = JSONArray.parseObject(resultString);
                JSONArray jsonArray = JSON.parseArray(resultString);
                log.info("jsonArray:"+jsonArray.size());
                if(jsonArray.size()>0){
                    responseJson = jsonArray.getJSONObject(0); // 假设总是处理第一个元素
                }

            }

        } catch (Exception e) {
            log.error("GET请求异常", e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException ex) {
                log.error("关闭资源时异常", ex);
            }
        }
        return responseJson;
    }

    /**
     * 发送POST请求，忽略SSL验证
     * @param url 请求URL
     * @param param 请求参数
     * @return 返回的JSON响应对象
     */
    public static JSONObject sendPostCHN(String url, String param) {
        System.out.println(url);
        System.out.println(param);
        JSONObject response = null;
        try {
            URL realUrl = new URL(url);
            HttpURLConnection httpConn = (HttpURLConnection) realUrl.openConnection();

            // 忽略SSL验证
            if ("https".equalsIgnoreCase(realUrl.getProtocol())) {
                trustAllHosts((HttpsURLConnection) httpConn);
            }

            httpConn.setRequestProperty("accept", "*/*");
            httpConn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            httpConn.setRequestMethod("POST");

            try (PrintWriter out = new PrintWriter(new OutputStreamWriter(httpConn.getOutputStream(), StandardCharsets.UTF_8))) {
                out.print(param);
                out.flush();
            }

            try (BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder responseBuilder = new StringBuilder();
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    responseBuilder.append(inputLine);
                }
                String result = responseBuilder.toString();
                response = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            System.err.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
        }
        return response;
    }

    // 忽略所有SSL主机验证
    private static void trustAllHosts(HttpsURLConnection conn) {
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            }};

            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier((hostname, session) -> true);
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }
    }
    //调用
    public static void main(String arg[]) throws Exception {

        try {
            JSONObject response = sendPostCHN("https://example.com/api/data", "{\"key\":\"value\"}");
            // System.out.println(response.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
